Lecture 1. Introduction to Tensorflow

Deep Learning Library

Theano, Torch, Tensorflow가 가장 많이 사용되는 lib

Software Creator Opensource Interface
Apache SINGA Apache Incubator Yes Python, C++, Java
Caffe Berkeley Vision and Learning Center Yes Python, MATLAB
Deeplearning4j Skymind engineering team; Deeplearning4j community; originally Adam Gibson Yes Java, Scala, Clojure, Python (Keras)
Dlib Davis King Yes C++
Keras François Chollet Yes Python
Microsoft Cognitive Toolkit Microsoft Research Yes Python, C++, Command line, BrainScript (.NET on roadmap)
MXNet Distributed (Deep) Machine Learning Community Yes C++, Python, Julia, Matlab, JavaScript, Go, R, Scala, Perl
Neural Designer Artelnics No Graphical user interface
OpenNN Artelnics Yes C++
TensorFlow Google Brain team Yes Python (Keras), C/C++, Java, Go, R
Theano Université de Montréal Yes Python
Torch Ronan Collobert, Koray Kavukcuoglu, Clement Farabet Yes Lua, LuaJIT, C, utility library for C++/OpenCL
Wolfram Mathematica Wolfram Research Yes Command line, Java, C++

Why TensorFlow?

  • Python API
  • Portability: 단일 API를 사용하여 데스크톱, 서버 또는 모바일 장치의 하나 이상의 CPU 또는 GPU에서 계산 가능
  • Flexibility(유연성): from Raspberry Pi, Android, Windows, iOS, Linux to server farms
  • Visualization (TensorBoard)
  • Checkpoints (for managing experiments)

Getting started with one-liner Tensorflow

1. TF Learn(tf.contrib.learn)


In [1]:
# Load Module
import numpy as np
from sklearn import datasets
from sklearn import metrics
from sklearn import model_selection
import tensorflow as tf

In [2]:
# Load dataset.
iris = datasets.load_iris() # 총 150개의 붓꽃 사진과 class load
x_train, x_test, y_train, y_test = model_selection.train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
print('train and test ready')


train and test ready

In [3]:
x_train[:10]
# 각 열은 꽃받침 길이, 꽃받침 너비, 꽃잎 길이, 꽃잎 너비


Out[3]:
array([[ 4.6,  3.6,  1. ,  0.2],
       [ 5.7,  4.4,  1.5,  0.4],
       [ 6.7,  3.1,  4.4,  1.4],
       [ 4.8,  3.4,  1.6,  0.2],
       [ 4.4,  3.2,  1.3,  0.2],
       [ 6.3,  2.5,  5. ,  1.9],
       [ 6.4,  3.2,  4.5,  1.5],
       [ 5.2,  3.5,  1.5,  0.2],
       [ 5. ,  3.6,  1.4,  0.2],
       [ 5.2,  4.1,  1.5,  0.1]])

In [4]:
y_train[:10] # 0,1,2는 꽃의 종 의미


Out[4]:
array([0, 0, 1, 0, 0, 2, 1, 0, 0, 0])

In [6]:
# 10, 20, 10 단위로 각각 3층 DNN 생성
feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(x_train) # list feature column
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=3)


WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.
INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpcq20amc_
INFO:tensorflow:Using config: {'_environment': 'local', '_keep_checkpoint_every_n_hours': 10000, '_model_dir': '/tmp/tmpcq20amc_', '_evaluation_master': '', '_task_type': None, '_tf_config': gpu_options {
  per_process_gpu_memory_fraction: 1.0
}
, '_keep_checkpoint_max': 5, '_num_ps_replicas': 0, '_save_checkpoints_secs': 600, '_is_chief': True, '_tf_random_seed': None, '_session_config': None, '_master': '', '_save_summary_steps': 100, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f8dea5a4400>, '_save_checkpoints_steps': None, '_task_id': 0, '_num_worker_replicas': 0}

In [9]:
# Train.
classifier.fit(x_train, y_train, steps=200)
predictions = list(classifier.predict(x_test, as_iterable=True))


WARNING:tensorflow:From <ipython-input-9-6b0c48bbf3cc>:2: calling BaseEstimator.fit (from tensorflow.contrib.learn.python.learn.estimators.estimator) with y is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
WARNING:tensorflow:From <ipython-input-9-6b0c48bbf3cc>:2: calling BaseEstimator.fit (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.
WARNING:tensorflow:From /home/seongcheolkim/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/head.py:625: scalar_summary (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2016-11-30.
Instructions for updating:
Please switch to tf.summary.scalar. Note that tf.summary.scalar uses the node name instead of the tag. This means that TensorFlow will automatically de-duplicate summary names based on the scope they are created in. Also, passing a tensor or list of tags to a scalar summary op is no longer supported.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Saving checkpoints for 1 into /tmp/tmpcq20amc_/model.ckpt.
INFO:tensorflow:loss = 1.03969, step = 1
INFO:tensorflow:global_step/sec: 923.809
INFO:tensorflow:loss = 0.137468, step = 101 (0.108 sec)
INFO:tensorflow:Saving checkpoints for 200 into /tmp/tmpcq20amc_/model.ckpt.
INFO:tensorflow:Loss for final step: 0.0797015.
WARNING:tensorflow:From /home/seongcheolkim/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py:347: calling DNNClassifier.predict (from tensorflow.contrib.learn.python.learn.estimators.dnn) with outputs=None is deprecated and will be removed after 2017-03-01.
Instructions for updating:
Please switch to predict_classes, or set `outputs` argument.
WARNING:tensorflow:From /home/seongcheolkim/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py:433: calling BaseEstimator.predict (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.
INFO:tensorflow:Restoring parameters from /tmp/tmpcq20amc_/model.ckpt-200

In [10]:
# Score with sklearn.
score = metrics.accuracy_score(y_test, predictions)
print('Accuracy: {0:f}'.format(score))


Accuracy: 0.966667

In [11]:
new_samples = np.array(
    [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = list(classifier.predict(new_samples, as_iterable=True))


WARNING:tensorflow:From /home/seongcheolkim/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py:347: calling DNNClassifier.predict (from tensorflow.contrib.learn.python.learn.estimators.dnn) with outputs=None is deprecated and will be removed after 2017-03-01.
Instructions for updating:
Please switch to predict_classes, or set `outputs` argument.
WARNING:tensorflow:From /home/seongcheolkim/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py:433: calling BaseEstimator.predict (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.
INFO:tensorflow:Restoring parameters from /tmp/tmpcq20amc_/model.ckpt-200

In [12]:
print('Predictions: {}'.format(str(y)))


Predictions: [1, 2]

2. TF-slim(tf.contrib.slim)

  • Contrib 중 하나의 library로, 상위 수준의 개념(argument scoping, layer, variable)으로 모델을 짧고 쉽게 정의할 수 있게 만듦
  • 많이 사용되는 regularizer를 사용하여 모델을 단순하게 함. VGG, AlexNet과 같이 많이 쓰이는 모델을 개발 해놓음

without TF-Slim


In [ ]:
input = ...
with tf.name_scope('conv1_1') as scope:
    kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32,
                                           stddev=1e-1), name='weights')
    conv = tf.nn.conv2d(input, kernel, [1, 1, 1, 1], padding='SAME')
    biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32),
                       trainable=True, name='biases')
    bias = tf.nn.bias_add(conv, biases)
    conv1 = tf.nn.relu(bias, name=scope)

with TF-Slim


In [ ]:
input = ...
net = slim.conv2d(input, 128, [3, 3], scope='conv1_1')

Data Flow Graph


In [1]:
import tensorflow as tf

In [2]:
a = tf.add(2, 3)

In [3]:
a = tf.add(3, 5)

In [4]:
print (a)


Tensor("Add_1:0", shape=(), dtype=int32)

How to get the value of a?

  • Session을 시작해줘야 operation이 작동함

In [5]:
sess = tf.Session()
sess.run(a)


Out[5]:
8

In [17]:
a = tf.add(3, 5)

with tf.Session() as sess:
    print (sess.run(a))


8

More graphs


In [18]:
x = 2
y = 3

op1 = tf.add(x, y)
op2 = tf.multiply(x, y)
useless = tf.multiply(x, op1)
op3 = tf.pow(op2, op1)

with tf.Session() as sess:
    op3 = sess.run(op3)

In [4]:
x = 2
y = 3

op1 = tf.add(x, y)
op2 = tf.multiply(x, y)
useless = tf.multiply(x, op1)
op3 = tf.pow(op2, op1)

with tf.Session() as sess:
    op3, not_useless = sess.run([op3, useless])

In [8]:
# Creates a graph.

with tf.device("/cpu:0"): # 연산장치 선택 가능
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape = [2,3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape = [3,2], name='b')
    c = tf.matmul(a, b) 
    
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) # tf.ConfigProto(log_device_placement=True) cpu와 gpu연산이 모두 가능할 때 gpu선택

# Runs the op.
print (sess.run(a))
print (sess.run(b))
print (sess.run(c))


[[ 1.  2.  3.]
 [ 4.  5.  6.]]
[[ 1.  2.]
 [ 3.  4.]
 [ 5.  6.]]
[[ 22.  28.]
 [ 49.  64.]]

Why graphs

  • 계산 저장 가능
  • 계산을 작은 단위로 나누어 자동차별화를 용이하게 해줌
  • 분산 컴퓨팅을 가능케하고 CPU, GPU 혹은 여러 장치를 한번에 사용할 수 있게 해줌
  • 많은 기계학습 모델들이 이미 그래프를 통해 가르쳐지고 시각화되고 있기 때문

Lecture 2: Tensorflow Ops

1. Fun with TensorBoard

텐서보드 활성화를 위해 그래프의 학습루프가 실행되기 전 코드 삽입

  • writer = tf.summary.FileWriter(logs_dir, sess.graph)
  • tf.train.FileWriter -> 에러
  • tf.train.SummaryWriter -> 에러
  • 이벤트의 로그가 지정된 폴더에 저장됨

In [9]:
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
with tf.Session() as sess:
    writer = tf.summary.FileWriter('./graphs', sess.graph) # 텐서보드에서 볼 수 있는 그래프 저장
    print (sess.run(x))

    # close the writer when you’re done using it
writer.close()


5

텐서보드 실행법

  • 터미널에서
  • python [yourprogram.py]
  • tensorboard --logdir="./graphs"
  • http://localhost:6006/ 로 이동

  • jupyter 터미널에서도 실행 가능

  • 윈도우버전 jupyter 실행 불가

2. Constant types


In [10]:
# constant of 1d tensor (vector)
a = tf.constant([2, 2], name="vector")

# constant of 2x2 tensor (matrix)
b = tf.constant([[0, 1], [2, 3]], name="b")

In [11]:
with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(b))


[2 2]
[[0 1]
 [2 3]]
  • 텐서의 원소로 특정한 값을 생성할 수 있음
  • 유사함수: numpy.zeros, numpy.zeros_like, numpy.ones, numpy.ones_like

tf.zero(shape, dtype=tf.float32, name=None)

  • 모든 원소가 0인 텐서쉐입을 만드는 함수

In [54]:
with tf.Session() as sess:
    print (sess.run(tf.zeros([2, 3], tf.int32))) # [[0, 0, 0], [0, 0, 0]]


[[0 0 0]
 [0 0 0]]

In [12]:
import numpy as np

In [13]:
np.zeros((2,3), dtype=np.int32)


Out[13]:
array([[0, 0, 0],
       [0, 0, 0]])

tf.zeros_like(input, dtype=None, name=None, opitmize=True)

  • 모든 원소를 0으로 만드는 함수

In [14]:
input_tensor = [[0, 1], [2, 3], [4, 5]]

with tf.Session() as sess:
    print (sess.run(tf.zeros_like(input_tensor)))  # [[0, 0], [0, 0], [0, 0]]


[[0 0]
 [0 0]
 [0 0]]

In [27]:
np.zeros_like(input_tensor)


Out[27]:
array([[0, 0],
       [0, 0],
       [0, 0]])

tf.one(shape, dtype=tf.float32, name=None)

  • 모든 원소가 1인 텐서쉐입을 만드는 함수

In [57]:
with tf.Session() as sess:
    print(sess.run(tf.ones([2, 3], tf.int32))) # [[1, 1, 1], [1, 1, 1]]


[[1 1 1]
 [1 1 1]]

In [28]:
np.ones([2,3], dtype=np.int32)


Out[28]:
array([[1, 1, 1],
       [1, 1, 1]], dtype=int32)

tf.ones_like(input_tensor, dtype=None, name=None, optimize=True)

  • 모든 원소를 1로 만드는 함수

In [58]:
input_tensor = [[0, 1], [2, 3], [4, 5]]
with tf.Session() as sess:
    print(sess.run(tf.ones_like(input_tensor))) # [[1, 1], [1, 1], [1, 1]]


[[1 1]
 [1 1]
 [1 1]]

In [29]:
np.ones_like(input_tensor)


Out[29]:
array([[1, 1],
       [1, 1],
       [1, 1]])

tf.fill(dims, value, name=None)

  • 텐서를 한가지 스칼라값으로 채움

In [61]:
with tf.Session() as sess:
    print(sess.run(tf.fill([2, 3], 8))) # [[8, 8, 8], [8, 8, 8]]


[[8 8 8]
 [8 8 8]]

tf.linspace(start, stop, num, name=None)

  • 특정 구간에서 균등하게 증가(개수만큼)하는 수열 생성

In [62]:
with tf.Session() as sess:
    print(sess.run(tf.linspace(10.0, 13.0, 4, name="linspace"))) # [10.0 11.0 12.0 13.0]


[ 10.  11.  12.  13.]

tf.range(start, limit=None, delta=1, dtype=None, name='range')

  • 등차수열 생성

In [63]:
with tf.Session() as sess:
    print(sess.run(tf.range(3, 18, 3))) # [3, 6, 9, 12, 15]


[ 3  6  9 12 15]

텐서는 반복문에 사용할 수 없음


In [67]:
for _ in range(4):# OK
    a

In [68]:
for _ in tf.range(4): # TypeError("'Tensor' object is not iterable.")
    a


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-40a26e31645b> in <module>()
----> 1 for _ in tf.range(4): # TypeError("'Tensor' object is not iterable.")
      2     a

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in __iter__(self)
    539       TypeError: when invoked.
    540     """
--> 541     raise TypeError("'Tensor' object is not iterable.")
    542 
    543   def __bool__(self):

TypeError: 'Tensor' object is not iterable.

특정 분포에서 난수를 생성할 수 있음

  • tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
    • 정규분포로부터의 난수 생성

  • tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None,name=None)
    • 절단정규분포로부터의 난수 생성

  • tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,name=None)
    • 균등분포로부터의 난수 생성

  • tf.multinomial(logits, num_samples, seed=None, name=None)
    • 다항분포로부터의 난수 생성

  • tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=None)
    • 감마분포로부터의 난수 생성

  • tf.random_shuffle(value, seed=None, name=None)
    • 값의 첫번째 차원을 기준으로 랜덤하게 섞어줌

  • tf.random_crop(value, size, seed=None, name=None)
    • 텐서를 주어진 value만큼 랜덤하게 잘라냄

In [45]:
with tf.Session() as sess:
    print(sess.run(tf.random_normal(shape = [2,3])))


[[-0.27190062 -0.5285061  -0.09924424]
 [-0.13434738 -2.10485244 -0.91244501]]

In [46]:
with tf.Session() as sess:
    print(sess.run(tf.truncated_normal(shape = [2,3])))


[[ 0.7165556   0.18927738 -0.65542114]
 [-0.30164579  0.27111992  0.14996052]]

In [52]:
with tf.Session() as sess:
    print(sess.run(tf.multinomial(tf.random_normal(shape = [2,3]),5)))


[[1 1 1 1 0]
 [2 0 1 0 2]]

In [51]:
with tf.Session() as sess:
    print(sess.run(tf.random_gamma(shape = [2,3], alpha = 1)))


[[ 1.08338523  0.86620259  1.09026694]
 [ 0.38374829  1.04365468  1.90339291]]

In [58]:
a = tf.constant([[2,1], [3,2], [7,3]])

In [42]:
with tf.Session() as sess:
    print(sess.run(tf.random_shuffle(a)))


[[2 1]
 [7 3]
 [3 2]]

In [65]:
with tf.Session() as sess:
    print(sess.run(tf.random_crop(a, [2,1])))


[[2]
 [3]]

3. Math Operations


In [26]:
a = tf.constant([3, 6])
b = tf.constant([2, 2])

In [27]:
with tf.Session() as sess:
    print(sess.run(tf.add(a, b))) # >> [5 8], 2개의 input을 받아 덧셈


[5 8]

In [28]:
with tf.Session() as sess:
    print(sess.run(tf.add_n([a, b, b]))) # >> [7 10]. 모든 input을 덧셈


[ 7 10]

In [29]:
with tf.Session() as sess:
    print(sess.run(tf.multiply(a, b))) # >> [6 12] because mul is element wise


[ 6 12]

In [31]:
# matmul: 2차원이상의 텐서간의 곱
with tf.Session() as sess:
    print(sess.run(tf.matmul(tf.reshape(a, shape=[1, 2]), 
          tf.reshape(b, shape=[2, 1]))))


[[18]]

In [32]:
with tf.Session() as sess:
    print(sess.run(tf.div(a, b))) # >> [1 3], 나눗셈 실행


[1 3]

In [33]:
with tf.Session() as sess:
    print(sess.run(tf.mod(a, b))) # >> [1 0], 나머지 반환


[1 0]

4. Data Types

Python Native Types : 불린, 숫자, 스트링

  • 단일 값은 0차원 텐서 (스칼라)
  • 값의 리스트는 1차원 텐서 (벡터)
  • 리스트의 리스트는 2차원 텐서 (매트릭스)

In [78]:
# 0차원 상수텐서 - 스칼라
t_0 = 19

with tf.Session() as sess:
    print(sess.run(tf.zeros_like(t_0))) # ==> 0
    print(sess.run(tf.ones_like(t_0))) # ==> 1


0
1

In [79]:
# 1차원 텐서 - 벡터
t_1 = [b"apple", b"peach", b"grape"]
with tf.Session() as sess:
    print(sess.run(tf.zeros_like(t_1))) # ==> ['' '' '']
    print(sess.run(tf.ones_like(t_1))) # ==> TypeError: Expected string, got 1 of type 'int' instead.


[b'' b'' b'']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in __init__(self, dims)
    427       try:
--> 428         dims_iter = iter(dims)
    429       except TypeError:

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in __iter__(self)
    540     """
--> 541     raise TypeError("'Tensor' object is not iterable.")
    542 

TypeError: 'Tensor' object is not iterable.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py in ones(shape, dtype, name)
   1490     try:
-> 1491       shape = tensor_shape.as_shape(shape)
   1492       output = constant(one, shape=shape, dtype=dtype, name=name)

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in as_shape(shape)
    797   else:
--> 798     return TensorShape(shape)
    799 

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in __init__(self, dims)
    430         # Treat as a singleton dimension
--> 431         self._dims = [as_dimension(dims)]
    432       else:

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in as_dimension(value)
    375   else:
--> 376     return Dimension(value)
    377 

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in __init__(self, value)
     31     else:
---> 32       self._value = int(value)
     33       if (not isinstance(value, compat.bytes_or_text_types) and

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Tensor'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-79-16bce9596e50> in <module>()
      3 with tf.Session() as sess:
      4     print(sess.run(tf.zeros_like(t_1))) # ==> ['' '' '']
----> 5     print(sess.run(tf.ones_like(t_1))) # ==> TypeError: Expected string, got 1 of type 'int' instead.

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py in ones_like(tensor, dtype, name, optimize)
   1460     if dtype is None:
   1461       dtype = tensor.dtype
-> 1462     ret = ones(ones_shape, dtype=dtype, name=name)
   1463     ret.set_shape(tensor.get_shape())
   1464     return ret

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py in ones(shape, dtype, name)
   1493     except (TypeError, ValueError):
   1494       shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
-> 1495       output = fill(shape, constant(one, dtype=dtype), name=name)
   1496   assert output.dtype.base_dtype == dtype
   1497   return output

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape)
    100   tensor_value = attr_value_pb2.AttrValue()
    101   tensor_value.tensor.CopyFrom(
--> 102       tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    103   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    104   const_tensor = g.create_op(

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    372       nparray = np.empty(shape, dtype=np_dt)
    373     else:
--> 374       _AssertCompatible(values, dtype)
    375       nparray = np.array(values, dtype=np_dt)
    376       # check to them.

~/miniconda3/envs/ml_python/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py in _AssertCompatible(values, dtype)
    300     else:
    301       raise TypeError("Expected %s, got %s of type '%s' instead." %
--> 302                       (dtype.name, repr(mismatch), type(mismatch).__name__))
    303 
    304 

TypeError: Expected string, got 1 of type 'int' instead.

In [68]:
# 2차원 텐서 - 메트릭스
t_2 = [[True, False, False],
       [False, False, True],
       [False, True, False]]

with tf.Session() as sess:
    print(sess.run(tf.zeros_like(t_2))) # ==> 2x2 tensor, 모든 원소값 False
    print(sess.run(tf.ones_like(t_2))) # ==> 2x2 tensor, 모든 원소값 True


[[False False False]
 [False False False]
 [False False False]]
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]]

TensorFlow Native Types

5. Variables

  • 변수는 할당될수 있고 변경 될수 있음
  • 상수는 그래프에 값이 저장되어 있어 그래프를 로딩할때 함께 로딩됨
  • 변수는 그래프와 별도로 저장됨(파라미터 서버에 살고 있음)

In [84]:
my_const = tf.constant([1.0, 2.0], name="my_const")
print (tf.get_default_graph().as_graph_def())


node {
  name: "Add/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Add/y"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add"
  op: "Add"
  input: "Add/x"
  input: "Add/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Mul/y"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Mul"
  op: "Mul"
  input: "Mul/x"
  input: "Mul/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_1/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Mul_1"
  op: "Mul"
  input: "Mul_1/x"
  input: "Add"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Pow"
  op: "Pow"
  input: "Mul"
  input: "Add"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Add_1/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Add_1/y"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add_1"
  op: "Add"
  input: "Add_1/x"
  input: "Add_1/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_2/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Mul_2/y"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Mul_2"
  op: "Mul"
  input: "Mul_2/x"
  input: "Mul_2/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_3/x"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Mul_3"
  op: "Mul"
  input: "Mul_3/x"
  input: "Add_1"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Pow_1"
  op: "Pow"
  input: "Mul_2"
  input: "Add_1"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "a"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        tensor_content: "\000\000\200?\000\000\000@\000\000@@\000\000\200@\000\000\240@\000\000\300@"
      }
    }
  }
}
node {
  name: "b"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\200?\000\000\000@\000\000@@\000\000\200@\000\000\240@\000\000\300@"
      }
    }
  }
}
node {
  name: "MatMul"
  op: "MatMul"
  input: "a"
  input: "b"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "transpose_a"
    value {
      b: false
    }
  }
  attr {
    key: "transpose_b"
    value {
      b: false
    }
  }
}
node {
  name: "Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Const_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Const_2"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add_2"
  op: "Add"
  input: "Const_1"
  input: "Const_2"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_3"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Const_4"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add_3"
  op: "Add"
  input: "Const_3"
  input: "Const_4"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_5"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Const_6"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add_4"
  op: "Add"
  input: "Const_5"
  input: "Const_6"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_7"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 2
      }
    }
  }
}
node {
  name: "Const_8"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "Add_5"
  op: "Add"
  input: "Const_7"
  input: "Const_8"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "vector"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "b_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "zeros"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "zeros_like/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000\004\000\000\000\005\000\000\000"
      }
    }
  }
}
node {
  name: "zeros_like"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "ones"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000\004\000\000\000\005\000\000\000"
      }
    }
  }
}
node {
  name: "ones_like/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "ones_like/Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like"
  op: "Fill"
  input: "ones_like/Shape"
  input: "ones_like/Const"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Fill/dims"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "Fill/value"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 8
      }
    }
  }
}
node {
  name: "Fill"
  op: "Fill"
  input: "Fill/dims"
  input: "Fill/value"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "linspace/start"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 10.0
      }
    }
  }
}
node {
  name: "linspace/stop"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 13.0
      }
    }
  }
}
node {
  name: "linspace/num"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 4
      }
    }
  }
}
node {
  name: "linspace"
  op: "LinSpace"
  input: "linspace/start"
  input: "linspace/stop"
  input: "linspace/num"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "Tidx"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "range/start"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "range/limit"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 18
      }
    }
  }
}
node {
  name: "range/delta"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "range"
  op: "Range"
  input: "range/start"
  input: "range/limit"
  input: "range/delta"
  attr {
    key: "Tidx"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "ones_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_COMPLEX64
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_COMPLEX64
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        scomplex_val: 1.0
        scomplex_val: 0.0
      }
    }
  }
}
node {
  name: "Fill_1/dims"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "Fill_1/value"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 8
      }
    }
  }
}
node {
  name: "Fill_1"
  op: "Fill"
  input: "Fill_1/dims"
  input: "Fill_1/value"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_9"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_10"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_6"
  op: "Add"
  input: "Const_9"
  input: "Const_10"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN"
  op: "AddN"
  input: "Const_9"
  input: "Const_10"
  input: "Const_10"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_11"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_12"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_7"
  op: "Add"
  input: "Const_11"
  input: "Const_12"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN_1"
  op: "AddN"
  input: "Const_11"
  input: "Const_12"
  input: "Const_12"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_4"
  op: "Mul"
  input: "Const_11"
  input: "Const_12"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_13"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_14"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_8"
  op: "Add"
  input: "Const_13"
  input: "Const_14"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN_2"
  op: "AddN"
  input: "Const_13"
  input: "Const_14"
  input: "Const_14"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_5"
  op: "Mul"
  input: "Const_13"
  input: "Const_14"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_15"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_16"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_9"
  op: "Add"
  input: "Const_15"
  input: "Const_16"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN_3"
  op: "AddN"
  input: "Const_15"
  input: "Const_16"
  input: "Const_16"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_6"
  op: "Mul"
  input: "Const_15"
  input: "Const_16"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_17"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_18"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_10"
  op: "Add"
  input: "Const_17"
  input: "Const_18"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN_4"
  op: "AddN"
  input: "Const_17"
  input: "Const_18"
  input: "Const_18"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_7"
  op: "Mul"
  input: "Const_17"
  input: "Const_18"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Reshape/shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\001\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Reshape"
  op: "Reshape"
  input: "Const_17"
  input: "Reshape/shape"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "Tshape"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Reshape_1/shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\001\000\000\000"
      }
    }
  }
}
node {
  name: "Reshape_1"
  op: "Reshape"
  input: "Const_18"
  input: "Reshape_1/shape"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "Tshape"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "MatMul_3"
  op: "MatMul"
  input: "Reshape"
  input: "Reshape_1"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "transpose_a"
    value {
      b: false
    }
  }
  attr {
    key: "transpose_b"
    value {
      b: false
    }
  }
}
node {
  name: "div"
  op: "FloorDiv"
  input: "Const_17"
  input: "Const_18"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "FloorMod"
  op: "FloorMod"
  input: "Const_17"
  input: "Const_18"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "vector_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "b_2"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "zeros_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "zeros_like_1/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000\004\000\000\000\005\000\000\000"
      }
    }
  }
}
node {
  name: "zeros_like_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "ones_2"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like_1/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\000\000\001\000\000\000\002\000\000\000\003\000\000\000\004\000\000\000\005\000\000\000"
      }
    }
  }
}
node {
  name: "ones_like_1/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "ones_like_1/Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like_1"
  op: "Fill"
  input: "ones_like_1/Shape"
  input: "ones_like_1/Const"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Fill_2/dims"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "Fill_2/value"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 8
      }
    }
  }
}
node {
  name: "Fill_2"
  op: "Fill"
  input: "Fill_2/dims"
  input: "Fill_2/value"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "ones_3"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_COMPLEX64
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_COMPLEX64
        tensor_shape {
          dim {
            size: 2
          }
          dim {
            size: 3
          }
        }
        scomplex_val: 1.0
        scomplex_val: 0.0
      }
    }
  }
}
node {
  name: "Fill_3/dims"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "Fill_3/value"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 8
      }
    }
  }
}
node {
  name: "Fill_3"
  op: "Fill"
  input: "Fill_3/dims"
  input: "Fill_3/value"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "linspace_1/start"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 10.0
      }
    }
  }
}
node {
  name: "linspace_1/stop"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
        }
        float_val: 13.0
      }
    }
  }
}
node {
  name: "linspace_1/num"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 4
      }
    }
  }
}
node {
  name: "linspace_1"
  op: "LinSpace"
  input: "linspace_1/start"
  input: "linspace_1/stop"
  input: "linspace_1/num"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "Tidx"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "range_1/start"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "range_1/limit"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 18
      }
    }
  }
}
node {
  name: "range_1/delta"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "range_1"
  op: "Range"
  input: "range_1/start"
  input: "range_1/limit"
  input: "range_1/delta"
  attr {
    key: "Tidx"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "range_2/start"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "range_2/limit"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 4
      }
    }
  }
}
node {
  name: "range_2/delta"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "range_2"
  op: "Range"
  input: "range_2/start"
  input: "range_2/limit"
  input: "range_2/delta"
  attr {
    key: "Tidx"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Const_19"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\006\000\000\000"
      }
    }
  }
}
node {
  name: "Const_20"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Add_11"
  op: "Add"
  input: "Const_19"
  input: "Const_20"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "AddN_5"
  op: "AddN"
  input: "Const_19"
  input: "Const_20"
  input: "Const_20"
  attr {
    key: "N"
    value {
      i: 3
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Mul_8"
  op: "Mul"
  input: "Const_19"
  input: "Const_20"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Reshape_2/shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\001\000\000\000\002\000\000\000"
      }
    }
  }
}
node {
  name: "Reshape_2"
  op: "Reshape"
  input: "Const_19"
  input: "Reshape_2/shape"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "Tshape"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "Reshape_3/shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\002\000\000\000\001\000\000\000"
      }
    }
  }
}
node {
  name: "Reshape_3"
  op: "Reshape"
  input: "Const_20"
  input: "Reshape_3/shape"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "Tshape"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "MatMul_5"
  op: "MatMul"
  input: "Reshape_2"
  input: "Reshape_3"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "transpose_a"
    value {
      b: false
    }
  }
  attr {
    key: "transpose_b"
    value {
      b: false
    }
  }
}
node {
  name: "div_1"
  op: "FloorDiv"
  input: "Const_19"
  input: "Const_20"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "FloorMod_1"
  op: "FloorMod"
  input: "Const_19"
  input: "Const_20"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "zeros_like_2/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 19
      }
    }
  }
}
node {
  name: "zeros_like_2"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "ones_like_2/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 19
      }
    }
  }
}
node {
  name: "ones_like_2/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
          }
        }
      }
    }
  }
}
node {
  name: "ones_like_2/Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like_2"
  op: "Fill"
  input: "ones_like_2/Shape"
  input: "ones_like_2/Const"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "zeros_like_3/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 19
      }
    }
  }
}
node {
  name: "zeros_like_3"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 0
      }
    }
  }
}
node {
  name: "ones_like_3/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 19
      }
    }
  }
}
node {
  name: "ones_like_3/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
          }
        }
      }
    }
  }
}
node {
  name: "ones_like_3/Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "ones_like_3"
  op: "Fill"
  input: "ones_like_3/Shape"
  input: "ones_like_3/Const"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "zeros_like_4/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_STRING
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: 3
          }
        }
        string_val: "apple"
        string_val: "peach"
        string_val: "grape"
      }
    }
  }
}
node {
  name: "zeros_like_4"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_STRING
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: 3
          }
        }
        string_val: ""
      }
    }
  }
}
node {
  name: "ones_like_4/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_STRING
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: 3
          }
        }
        string_val: "apple"
        string_val: "peach"
        string_val: "grape"
      }
    }
  }
}
node {
  name: "ones_like_4/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 1
          }
        }
        int_val: 3
      }
    }
  }
}
node {
  name: "zeros_like_5/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_BOOL
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_BOOL
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 3
          }
        }
        bool_val: true
        bool_val: false
        bool_val: false
        bool_val: false
        bool_val: false
        bool_val: true
        bool_val: false
        bool_val: true
        bool_val: false
      }
    }
  }
}
node {
  name: "zeros_like_5"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_BOOL
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_BOOL
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 3
          }
        }
        bool_val: false
      }
    }
  }
}
node {
  name: "ones_like_5/tensor"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_BOOL
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_BOOL
        tensor_shape {
          dim {
            size: 3
          }
          dim {
            size: 3
          }
        }
        bool_val: true
        bool_val: false
        bool_val: false
        bool_val: false
        bool_val: false
        bool_val: true
        bool_val: false
        bool_val: true
        bool_val: false
      }
    }
  }
}
node {
  name: "ones_like_5/Shape"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\003\000\000\000\003\000\000\000"
      }
    }
  }
}
node {
  name: "ones_like_5/Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_BOOL
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_BOOL
        tensor_shape {
        }
        bool_val: true
      }
    }
  }
}
node {
  name: "ones_like_5"
  op: "Fill"
  input: "ones_like_5/Shape"
  input: "ones_like_5/Const"
  attr {
    key: "T"
    value {
      type: DT_BOOL
    }
  }
}
node {
  name: "my_const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\200?\000\000\000@"
      }
    }
  }
}
node {
  name: "my_const_1"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: 2
          }
        }
        tensor_content: "\000\000\200?\000\000\000@"
      }
    }
  }
}
versions {
  producer: 22
}

Declare variables

  • tf.Variable 함수로 생성

In [85]:
# a를 스칼라 값으로 생성
a = tf.Variable(2, name="scalar")

# b를 벡터로 생성
b = tf.Variable([2, 3], name="vector")

# c를 2x2 matrix로 생성
c = tf.Variable([[0, 1], [2, 3]], name="matrix")

# W를 0으로 채워진 784x10 tensor로 생성
W = tf.Variable(tf.zeros([784,10]))
  • 변수를 사용하기 전에는 항상 변수를 초기화해야함
  • tf.global_variables_initializer() 함수는 모든 변수를 초기화해줌

In [88]:
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
  • To initialize only as subset of varuables
  • tf.variables_initializer()

In [92]:
init_ab = tf.variables_initializer([a, b], name = "init_ab")
with tf.Session() as sess:
    sess.run(init)

Evaluate values of variables

  • 그냥 프린트하면 텐서와 유형, 쉐입만 볼수 있음

In [16]:
W = tf.Variable(tf.truncated_normal([700, 10]))

with tf.Session() as sess:
    sess.run(W.initializer)
    print (W)


Tensor("Variable/read:0", shape=(700, 10), dtype=float32)
  • eval()함수를 사용하면 값까지 볼수 있음

In [17]:
with tf.Session() as sess:
    sess.run(W.initializer)
    print (W.eval())


[[ 0.53491747 -0.97214603 -0.25362843 ..., -0.33080781  0.71210492
   0.15845299]
 [-0.85256094  0.15077451  0.35028926 ..., -1.23960936 -0.43727723
  -1.09042752]
 [-0.04116889 -0.45859033 -0.30255347 ..., -1.1672219  -1.0055542
   1.1732012 ]
 ..., 
 [ 0.61147153 -0.59353799 -0.77846193 ..., -0.59030181  0.81388646
  -1.04443479]
 [-0.25231853 -1.03276289  0.10153459 ..., -0.50856006  0.42159763
  -0.35974124]
 [ 0.23649797  1.17891943 -1.44100964 ..., -0.93688089  0.81465119
  -0.14550973]]

Assign values to variables

  • tf.Variable.assign()함수를 사용함

In [18]:
W = tf.Variable(10)
W.assign(100) # 100이 W에 할당되지 않음

with tf.Session() as sess:
    sess.run(W.initializer)
    print (W.eval()) # >> 10


10

In [19]:
W = tf.Variable(10)
assign_op = W.assign(100) # assign이 W를 initialize시킴

with tf.Session() as sess:
    sess.run(assign_op)
    print (W.eval()) # >> 100


100

In [105]:
# 값이 2인 변수 a 생성
a = tf.Variable(2, name="scalar")

# a_times_two에 a * 2 할당
a_times_two = a.assign(a * 2)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init) # a_times_two가 a에 따라 바뀌기 때문에 반드시 a를 initialize시켜줘야 함
    sess.run(a_times_two) # >> 4
#     sess.run(a_times_two) # >> 8
#     sess.run(a_times_two) # >> 16
    print (a_times_two.eval())


8

In [107]:
W = tf.Variable(10)

with tf.Session() as sess:
    sess.run(W.initializer) # assign_add와 assign_sub는 assign과는 다르게 variable을 initialize시켜주지 않음
    print(sess.run(W.assign_add(10)))
    print(sess.run(W.assign_sub(2)))


20
18
  • Tensorflow session은 각각 유지됨
  • 각각의 session은 그래프에서 정의된 변수들의 현재값을 각각 가질 수 있다

In [20]:
W = tf.Variable(10)

sess1 = tf.Session()
sess2 = tf.Session()

sess1.run(W.initializer)
sess2.run(W.initializer)

print(sess1.run(W.assign_add(10))) # ==> 20
print(sess2.run(W.assign_sub(2))) # ==> 8

print(sess1.run(W.assign_add(100))) # ==> 120
print(sess2.run(W.assign_sub(50))) # ==> -42

sess1.close()
sess2.close()


20
8
120
-42
  • 다른 변수를 사용해서 변수를 만들수 있음

In [108]:
W = tf.Variable(tf.truncated_normal([700, 10]))
U = tf.Variable(W * 2)

6. InteractiveSession

  • 인터렉티브 세션은 그것 자체로 디폴트세션으로 작동함
  • 따로 run()을 선언하지 않아도 실행됨

In [21]:
sess = tf.InteractiveSession()
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

print(c.eval())
sess.close()


30.0

7. Control Dependencies

  • 두개 이상의 오퍼레이션이 존재할 때, 오퍼레이션의 실행 순서 지정
  • tf.Graph.control_dependencies(control_inputs) 함수사용

In [ ]:
# your graph g have 5 ops: a, b, c, d, e
with g.control_dependencies([a, b, c]):
    d = ....
    e = ....

8. Placeholders and feed_dict

  • 우리는 값을 알지 못하는 상태에서 그래프 먼저 그려야한다!
  • 그래프를 그리고 나중에 데이터를 공급해주기 위해 placeholder사용함 ### tf.placeholder(dtype, shape=None, name=None)

In [120]:
# create a placeholder of type float 32-bit, shape is a vector of 3 elements
a = tf.placeholder(tf.float32, shape=[3])

# create a constant of type float 32-bit, shape is a vector of 3 elements
b = tf.constant([5, 5, 5], tf.float32)

# use the placeholder as you would a constant or a variable
c = a + b # Short for tf.add(a, b)

with tf.Session() as sess:
    # feed [1, 2, 3] to placeholder a via the dict {a: [1, 2, 3]}
    # fetch value of c
    writer = tf.summary.FileWriter('./my_graph', sess.graph)
#     print(sess.run(c)) # ==> Error
    print(sess.run(c, {a: [1, 2, 3]}))


[ 6.  7.  8.]
  • 꼭 placeholder가 아니여도 feed 가능 ### tf.Graph.is_feedable(tensor)
  • 위의 함수를 사용하여 feed가능 여부를 확인할 수 있음

In [69]:
# create Operations, Tensors, etc (using the default graph)
a = tf.add(2, 5)
b = tf.multiply(a, 3)

# start up a `Session` using the default graph
sess = tf.Session()

# define a dictionary that says to replace the value of `a` with 15
replace_dict = {a: 15}

# Run the session, passing in `replace_dict` as the value to `feed_dict`
sess.run(b, feed_dict=replace_dict) # returns 45


Out[69]:
45

9. The trap of lazy loading

  • 속도를 조금 더 빠르게 해주는 팁
  • 연산을 최대한 뒤로 미루는 것

In [133]:
# Normal loading
x = tf.Variable(10, name='x')
y = tf.Variable(20, name='y')
z = tf.add(x, y)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter('./my_graph/l2', sess.graph)
    for _ in range(10):
        sess.run(z)
    
writer.close()

In [ ]:
# Lazy loading
x = tf.Variable(10, name='x')
y = tf.Variable(20, name='y')

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter('./my_graph/l2', sess.graph)
    for _ in range(10):
        sess.run(tf.add(x, y)) # someone decides to be clever to save one line of code
writer.close()